<?php
session_start();

$result = [
    'status' => 0,
    'data' => null,
    'message' => '未知错误'
];

include_once '../mysql/sql.php';
include_once 'select-fun.php';

if (isset($_SESSION['userid'])) {
    if (isset($sql) && $sql) {
        $params = [
            'userid' => $_SESSION['userid']
        ];

        $params['operation'] = isset($_GET['operation']) && ($_GET['operation'] === 'set') ? true : false;
        $params['money'] = isset($_GET['money']) ? $_GET['money'] : 0;

        // 总收入
        $params['incspe'] = 1;
        $total_inc = total_money($mysql, $params);
        if ($total_inc || $total_inc === null) {
            if ($total_inc !== null) {
                $total_inc = $total_inc[0]['totalMoney'];
            };
            // 总支出
            $params['incspe'] = -1;
            $total_spe = total_money($mysql, $params);
            if ($total_spe || $total_spe === null) {
                if ($total_spe !== null) {
                    $total_spe = $total_spe[0]['totalMoney'];
                };
                if ($params['operation']) {
                    // 设置
                    $params['money'] = $params['money'] + $total_spe - $total_inc;
                    $setBaseMoney = set_base_money($mysql, $params);
                    if ($setBaseMoney === 1) {
                        $result['status'] = 1;
                        $result['data'] = $params['money'];
                        $result['message'] = '设置成功';
                    }
                    else {
                        $result['status'] = 0;
                        $result['data'] = $params['money'];
                        $result['message'] = '设置失败';
                    };
                }
                else {
                    // 获取
                    $baseMoney = user_info($mysql, $params);
                    if ($baseMoney) {
                        $baseMoney = $baseMoney[0]['basemoney'];
                        $result['status'] = 1;
                        $result['data'] = $baseMoney + $total_inc - $total_spe;
                        $result['message'] = '获取余额成功';
                    }
                    else {
                        $result['status'] = 0;
                        $result['message'] = '获取基础金额失败';
                    };
                };
            }
            else {
                $result['status'] = 0;
                $result['message'] = '获取总支出失败';
            };
        }
        else {
            $result['status'] = 0;
            $result['message'] = '获取总收入失败';
        };
        
        // 关闭连接
        $mysql->close();
    }
    else {
        $result['message'] = '数据库连接错误';
    };
}
else {
    $result['message'] = '用户未登入';
};

echo json_encode($result);
?>